package com.example.examsystem.repository;

import com.example.examsystem.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    Optional<User> findByUsername(String username);
    
    Optional<User> findByEmail(String email);
    
    boolean existsByUsername(String username);
    
    boolean existsByEmail(String email);
    
    boolean existsByUsernameAndIdNot(String username, Long id);
    
    boolean existsByEmailAndIdNot(String email, Long id);

    /**
     * 查询用户
     * @param username 用户名
     * @param email 邮箱
     * @param enabled 是否启用
     * @param pageable 分页参数
     */
    @Query("""
       SELECT u FROM User u
       WHERE
           (:username IS NULL OR :username = '' OR LOWER(u.username) LIKE LOWER(CONCAT('%', :username, '%'))) AND
           (:email IS NULL OR :email = '' OR LOWER(u.email) LIKE LOWER(CONCAT('%', :email, '%'))) AND
           (:enabled IS NULL OR u.enabled = :enabled)
       """)
    Page<User> findByQuery(@Param("username") String username,
                          @Param("email") String email,
                          @Param("enabled") Boolean enabled,
                          Pageable pageable);
}
